package logic

import (
	"context"
	"fmt"
	"shopping/model/cache"
	"shopping/model/mysql"

	"shopping/shoppingrpc/internal/svc"
	"shopping/shoppingrpc/shoppingrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *shoppingrpc.CartAddRequest) (*shoppingrpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line
	var goods mysql.Goods
	err := mysql.DB.Where("id = ?", in.GoodsId).First(&goods).Error
	if err != nil {
		return nil, fmt.Errorf("商品不存在")
	}

	if int(in.Quantity) > goods.Stock {
		return nil, fmt.Errorf("库存不足")
	}

	if cache.CartUpdate(int(in.UserId), int(in.GoodsId)) {
		err = cache.UpdateCart(int(in.UserId), int(in.GoodsId), int(in.Quantity))
		if err != nil {
			return nil, fmt.Errorf("数据更新失败")
		}
	} else {
		goodsMap := map[string]interface{}{
			"goods_id": goods.ID,
			"name":     goods.Name,
			"price":    goods.Price,
			"image":    goods.Image,
			"quantity": in.Quantity,
		}
		err = cache.CartAdd(int(in.UserId), int(in.GoodsId), goodsMap)
		if err != nil {
			return nil, fmt.Errorf("购物车添加失败")
		}
	}

	return &shoppingrpc.CartAddResponse{
		Success: true,
		Message: "添加成功",
	}, nil
}
